import { liveViewManager } from '@kit.LiveViewKit';
import { Want, wantAgent } from '@kit.AbilityKit';
import { promptAction } from '@kit.ArkUI';
import { LogDomain, LogHelper } from '../utils/LogHelper';

const TAG: string = 'KitDemo-PUSH'
const logHelper: LogHelper = LogHelper.getLogHelper(LogDomain.DEBUG_MAIN, TAG);

export class NavigationLiveViewController {
  public static liveViewID: number

  //-2147483648, 2147483647
  public static getRandom(n: number, m: number) {
    return Math.floor(Math.random() * (m - n + 1) + n)
  }

  private static async buildDefaultView(id: number): Promise<liveViewManager.LiveView> {
    logHelper.showError('NavigationLiveViewController.liveViewID:'+ id)
    return {
      // 构造实况窗请求体
      id: id, // 实况窗ID，开发者生成。
      event: "NAVIGATION", // 实况窗的应用场景。NAVIGATION：导航。
      liveViewData: {
        primary: {
          title: "178米后左转",
          content: [
            { text: "去往" },
            { text: "南京东路", textColor: "#FF0A59F7" }
          ],
          keepTime: 15,
          clickAction: await NavigationLiveViewController.buildWantAgent(),
          layoutData: {
            layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_NAVIGATION,
            currentNavigationIcon: "navigation.png", // 当前导航方向，取值为“/resources/rawfile”路径下的文件名或image.PixelMap
            navigationIcons: ["left.png", "straight.png", "straight.png",
              "right.png"] // 导航方向的箭头集合图片，每个元素取值为“/resources/rawfile”路径下的文件名或image.PixelMap
          }
        }
      }
    };
  }

  private static async isLiveViewEnabled(): Promise<boolean> {
    return await liveViewManager.isLiveViewEnabled();
  }

  private static async buildWantAgent(): Promise<Want> {
    const wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [
        {
          bundleName: 'com.tdtech.kitdemo', // 应用实际bundleName
          abilityName: 'EntryAbility'
        } as Want
      ],
      actionType: wantAgent.OperationType.START_ABILITIES,
      requestCode: 0,
      actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
    };
    const agent = await wantAgent.getWantAgent(wantAgentInfo);
    return agent;
  }

  public async start(id: number): Promise<liveViewManager.LiveViewResult> {
    // let data = await NavigationLiveViewController.doRand()
    logHelper.showError('pushDemo_startLiveViewFunc')
    // console.log('pushDemo_startLiveView_ID:' + NavigationLiveViewController.getRandom(-2147483648, 2147483647).toString())
    // 校验实况窗开关是否打开
    let isEnabled = await NavigationLiveViewController.isLiveViewEnabled()
    logHelper.showError('pushDemo_startLiveView_isEnabled:'+ isEnabled)
    if (!isEnabled) {
      promptAction.showToast({ message: "实况窗未打开" })
      throw new Error("pushDemo_Live view is disabled.");
    }
    promptAction.showToast({ message: "实况窗开关已打开" })
    //获取实况窗数据
    const defaultView = await NavigationLiveViewController.buildDefaultView(id);
    //创建实况窗
    return await liveViewManager.startLiveView(defaultView);
  }
}